import { _decorator, Component, instantiate, Node, NodePool, Prefab, ScrollView, UITransform } from 'cc';
import { listItem } from './listItem';
const { ccclass, property } = _decorator;

@ccclass('virtualList')
export class virtualList extends Component {
    @property(ScrollView)
    scroll:ScrollView=null;

    @property(Node)
    view:Node=null;

    @property(Node)
    content:Node=null;

    @property(Prefab)
    itemPrefab:Prefab=null;

    maxCount=0;
    viewCount = 0;
    startIndex=0;
    currentIndex=0;
    endIndex=0;
    viewSize;
    listData=[];
    itemArray=[];
    poolNode:NodePool=new NodePool("ItemNode")
    start() {
        this.scroll.node.on(ScrollView.EventType.SCROLLING,this.onScroll,this);
        this.initVirtualtList();
    }
    initVirtualtList(){
        for(let i=0;i<30000;++i){
            this.listData[i] = {}
            this.listData[i].id = 100+i;
            this.listData[i].name = `test${100+i}`;
        }
        this.viewSize = this.view.getComponent(UITransform).contentSize;
        this.viewCount = Math.ceil(this.viewSize.height/60);
        this.maxCount = 2*Math.ceil(this.viewSize.height/60);       
        this.endIndex = this.maxCount;

        this.updateItem()

        let tran = this.content.getComponent(UITransform);
        tran.setContentSize(tran.contentSize.width,this.listData.length*60);
    }
    onScroll(){
        //范围更新
        const newIndex = Math.floor((this.content.position.y-this.viewSize.height/2)/60)        
        if(Math.abs(newIndex-this.currentIndex)>Math.floor(this.viewCount/3)){
            this.currentIndex=newIndex;
            this.startIndex=Math.max(0,this.currentIndex-this.viewCount);
            this.endIndex=Math.min(this.listData.length-1,this.currentIndex+this.maxCount); 
            console.log(this.startIndex,this.endIndex,newIndex,this.currentIndex)

            this.updateItem()          
        }
    }
    updateItem(){
        let itemNode = null;
        for(let i=0;i<this.itemArray.length;++i){
            if(this.itemArray[i]&&(i<this.startIndex||i>this.endIndex)){
                this.poolNode.put(this.itemArray[i]);
                this.itemArray[i]=null;
            }
        }
        //只渲染范围内
        for(let i=this.startIndex;i<=this.endIndex;++i){
            if(!this.itemArray[i]){
                if(this.poolNode.size()>0){
                    itemNode = this.poolNode.get();
                }
                else{
                    itemNode = instantiate(this.itemPrefab);
                }
                // console.log("setPosition=",i);
                itemNode.setPosition(0,i*(-60)-30);
                this.itemArray[i]=itemNode;
                this.content.addChild(this.itemArray[i]);
            }
            this.itemArray[i].getComponent(listItem).initData(this.listData[i]);  
        }
    }
    update(deltaTime: number) {
        
    }
}

